<?php
namespace addons\jieziarea\service;

use addons\jiezicommon\traits\Singleton;

class Area{
    use Singleton;
    public function getPcdByBaidu($lat, $lng){
        $return_data = [
            'province_id' => 0,
            'city_id' => 0,
            'district_id' => 0,
        ];
        if($lat && $lng){
            $url = 'http://api.map.baidu.com/geocoder/v2/?ak=' . config('app.baidu.ak') . '&location='.$lat.','.$lng.'&output=json&pois=1';
            $content = file_get_contents($url);
            $arr = json_decode($content,true);
            if($arr['status']){

            }else{
                $area_model = new \app\common\model\Area();
                if($arr['result']['addressComponent']['adcode']){
                    $return_data['district_id'] = $arr['result']['addressComponent']['adcode'];
                    $return_data['city_id'] = $area_model->cache('address_id_' . $return_data['district_id'], null, 'address_id_list')->where('id', $return_data['district_id'])->value('pid');
                    $return_data['province_id'] = $area_model->cache('address_id_' . $return_data['city_id'], null, 'address_id_list')->where('id', $return_data['city_id'])->value('pid');
                }
            }
        }
//        var_dump($arr);die;
//        $province = $arr['result']['addressComponent']['province'];
//        $city = $arr['result']['addressComponent']['city'];
//        $district = $arr['result']['addressComponent']['district'];
//        var_dump($province, $city, $district);die;
        return $return_data;
    }

    public function getPcdByGaode($lat, $lng){
        $return_data = [
            'province_id' => 0,
            'city_id' => 0,
            'district_id' => 0,
        ];
        $address = '';
        if($lng > 0 && $lat > 0){
            $url = 'https://restapi.amap.com/v3/geocode/regeo?output=json&location=' . $lng . ',' . $lat . '&key=' . config('app.gaode.key') . '&radius=1000&extensions=';

            $res = file_get_contents($url, false, stream_context_create(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]));
            $res = json_decode($res, true);
            if($res['status']){
                $area_model = new \app\common\model\Area();
                if($res['regeocode']['addressComponent']){
                    $return_data['district_id'] = $res['regeocode']['addressComponent']['adcode'];//高德的adcode和表中数据不匹配,比如鹿泉区(新启动),baidu是130185(鹿泉市,弃用)，gaode是
                    $return_data['city_id'] = $area_model->cache('address_id_' . $return_data['district_id'], null, 'address_id_list')->where('id', $return_data['district_id'])->value('pid');
                    $return_data['province_id'] = $area_model->cache('address_id_' . $return_data['city_id'], null, 'address_id_list')->where('id', $return_data['city_id'])->value('pid');
                }
//                $search = ['河北省', '衡水市', '河北', '衡水'];
//                $address = empty($res['regeocode']['formatted_address']) ? '' : str_replace($search, '', $res['regeocode']['formatted_address']);
            }
//            var_dump($res);die;
        }
        return $return_data;
    }

    /**
     * @param $level
     * formatted_address 格式化的地址
     * province 省份
     * city 城市
     * district 县区
     * township 村镇
     */
    public function getAddressByGaode($lat, $lng, $level = 'formatted_address'){
        $address = '';
        if($lng > 0 && $lat > 0){
            $url = 'https://restapi.amap.com/v3/geocode/regeo?output=json&location=' . $lng . ',' . $lat . '&key=' . config('app.gaode.key') . '&radius=1000&extensions=';

            $res = file_get_contents($url, false, stream_context_create(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]));
            $res = json_decode($res, true);//var_dump($res['regeocode']);
            if($res['status']){
                if($level == 'formatted_address'){
                    $address = $res['regeocode']['formatted_address'];
                }elseif(in_array($level, ['province', 'city', 'district', 'township', 'city'])){
                    $address = $res['regeocode']['addressComponent'][$level];
                }
            }
        }
        return $address;
    }

    /**
     * @param $level
     * formatted_address 格式化的地址
     * province 省份
     * city 城市
     * district 县区
     * township 村镇
     */


    /**
     * array(4) {
    ["status"]=>
    string(1) "1"
    ["regeocode"]=>
    array(2) {
    ["addressComponent"]=>
    array(12) {
    ["city"]=>
    array(0) {
    }
    ["province"]=>
    string(9) "北京市"
    ["adcode"]=>
    string(6) "110105"
    ["district"]=>
    string(9) "朝阳区"
    ["towncode"]=>
    string(12) "110105229000"
    ["streetNumber"]=>
    array(5) {
    ["number"]=>
    string(6) "101楼"
    ["location"]=>
    string(20) "116.518693,39.924296"
    ["direction"]=>
    string(6) "东南"
    ["distance"]=>
    string(7) "13.6739"
    ["street"]=>
    string(12) "朝阳北路"
    }
    ["country"]=>
    string(6) "中国"
    ["township"]=>
    string(9) "平房乡"
    ["businessAreas"]=>
    array(2) {
    [0]=>
    array(3) {
    ["location"]=>
    string(20) "116.513705,39.917963"
    ["name"]=>
    string(9) "甘露园"
    ["id"]=>
    string(6) "110105"
    }
    [1]=>
    array(3) {
    ["location"]=>
    string(20) "116.531484,39.899875"
    ["name"]=>
    string(12) "高碑店村"
    ["id"]=>
    string(6) "110105"
    }
    }
    ["building"]=>
    array(2) {
    ["name"]=>
    string(15) "朝阳大悦城"
    ["type"]=>
    string(32) "购物服务;商场;购物中心"
    }
    ["neighborhood"]=>
    array(2) {
    ["name"]=>
    array(0) {
    }
    ["type"]=>
    array(0) {
    }
    }
    ["citycode"]=>
    string(3) "010"
    }
    ["formatted_address"]=>
    string(42) "北京市朝阳区平房乡朝阳大悦城"
    }
    ["info"]=>
    string(2) "OK"
    ["infocode"]=>
    string(5) "10000"
    }
     */
    public function getAddressAndCodeByGaode($lat, $lng, $level = 'formatted_address'){
        $address = '';
        $code = '';
        if($lng > 0 && $lat > 0){
            $url = 'https://restapi.amap.com/v3/geocode/regeo?output=json&location=' . $lng . ',' . $lat . '&key=' . config('app.gaode.key') . '&radius=1000&extensions=';

            $res = file_get_contents($url, false, stream_context_create(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]));
            $res = json_decode($res, true);//var_dump($res['regeocode']);
            if($res['status']){
                if($level == 'formatted_address'){
                    $address = $res['regeocode']['formatted_address'];
                }elseif(in_array($level, ['province', 'city', 'district', 'township', 'city'])){
                    $address = $res['regeocode']['addressComponent'][$level];
                    if(empty($address) && $level == 'city'){
                        $address = $res['regeocode']['addressComponent']['province'];
                    }
                    $code = $res['regeocode']['addressComponent']['adcode'];
                }
            }
        }
        return [
            'address' => $address,
            'code' => $code
        ];
    }

    /**
     * 获取poi
     * @param $level
     * formatted_address 格式化的地址
     * province 省份
     * city 城市
     * district 县区
     * township 村镇
     */
    public function getPoiByGaode($keyword, $level = 'formatted_address'){
        $address = '';
        $code = '';
            $url = 'https://restapi.amap.com/v5/place/text?output=json&keywords=' . $keyword . '&key=' . config('gaode_key') . '&radius=1000&extensions=';

            $res = file_get_contents($url, false, stream_context_create(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]));
            $res = json_decode($res, true);//var_dump($res['regeocode']);
        var_dump($res);die;
            if($res['status']){
                if($level == 'formatted_address'){
                    $address = $res['regeocode']['formatted_address'];
                }elseif(in_array($level, ['province', 'city', 'district', 'township', 'city'])){
                    $address = $res['regeocode']['addressComponent'][$level];
                    $code = $res['regeocode']['addressComponent']['adcode'];
                }
            }
    }


    /**
     * @param $level
     * formatted_address 格式化的地址
     * province 省份
     * city 城市
     * district 县区
     * township 村镇
     */
    public function getAddressByQqmap($lat, $lng, $level = 'formatted_address'){
        $address = [];
        $addon_config = get_addon_config('jieziarea');
        $qqmap_service_key = empty($addon_config['qqmap_service_key']) ? '' : $addon_config['qqmap_service_key'];
        $qqmap_service_sk = empty($addon_config['qqmap_service_sk']) ? '' : $addon_config['qqmap_service_sk'];
//        if(empty($qqmap_service_key)){
            $qqmap_service_key = config('site.qqmap_service_key');
//        }
//        if(empty($qqmap_service_sk)){
            $qqmap_service_sk = config('site.qqmap_service_sk');
//        }
//        var_dump($qqmap_service_key, $qqmap_service_sk);
        if($lng > 0 && $lat > 0){
            $url = 'https://apis.map.qq.com/ws/geocoder/v1/?output=json&location=' . $lat . ',' . $lng . '&key=' . $qqmap_service_key . '&sig=' . md5('/ws/geocoder/v1/?key=' . $qqmap_service_key . '&location=' . $lat . ',' . $lng . '&output=json' . $qqmap_service_sk);

            $res = file_get_contents($url, false, stream_context_create(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]));
            $res = json_decode($res, true);//var_dump($res['regeocode']);

            if(!$res['status']){
//                dump($res);
//                echo 'formatted_addresses:' . $res['result']['formatted_addresses']['recommend'] . PHP_EOL;
                if($level == 'formatted_address'){
                    $address = $res['result']['formatted_addresses']['recommend'];
                }elseif($level == 'address'){
                    $address = $res['result']['address'];
                }elseif(in_array($level, ['province', 'city', 'district', 'street'])){
                    $address = $res['result']['address_component'][$level];
                }elseif($level == 'code'){
                    $address = [];
                    $area_model = new \app\common\model\Area();
                    if($res['result']['ad_info']['adcode']){
                        $address['district_id'] = $res['result']['ad_info']['adcode'];
                        $address['city_id'] = $area_model->where('id', $address['district_id'])->value('pid');
                        $address['province_id'] = $area_model->where('id', $address['city_id'])->value('pid');
                    }
                }elseif($level == 'city_name_code'){
                    $address = [];
                    $area_model = new \addons\jieziarea\model\Jieziarea();
                    if(!empty($res['result']['ad_info']['adcode'])){
                        $address = $area_model->alias('d')
                            ->join('jieziarea c', 'd.pid = c.id')
                            ->join('jieziarea p', 'c.pid = p.id')
                            ->where('d.id', $res['result']['ad_info']['adcode'])
                            ->field('c.id as city_id, c.name as city_name, d.id as district_id, d.name as district_name, p.id as province_id, p.name as province_name')->find();
                    }
                }elseif($level == 'city_name_code_index'){
                    $address = [];
                    $area_model = new \addons\jieziarea\model\Jieziarea();
                    if(!empty($res['result']['ad_info']['adcode'])){
                        $tmp_address = $area_model->where('id', $res['result']['ad_info']['adcode'])
                            ->field('id, pid, name')->find();
//                        var_dump($tmp_address);die;
                        if(!empty($tmp_address)){
//                            'city_id' => 0,
//                            'city_name' => '',
//                            'district_id' => 0,
//                            'district_name' => '',
//                            'province_id' => 0,
//                            'province_name' => '',
                            if($tmp_address['pid']){
                                $p_address = $area_model->where('id', $tmp_address['pid'])
                                    ->field('id, pid, name')->find();

                                if(!empty($p_address)){
                                    $p_p_address = $area_model->where('id', $p_address['pid'])
                                        ->field('id, pid, name')->find();
                                    if($p_p_address){
                                        $province_index = array_search($p_address['pid'], $area_model->where('level', 0)->column('id'));
                                        if($province_index !== false){
                                            $address['province_index'] = $province_index;
                                        }else{
                                            $address['province_index'] = 0;
                                        }
                                        $address['province_id'] = $p_address['pid'];
                                        $address['province_name'] = $p_p_address['name'];
                                        $city_index = array_search($tmp_address['pid'], $area_model->where('level', 1)->where('pid', $p_address['pid'])->column('id'));
                                        if($city_index !== false){
                                            $address['city_index'] = $city_index;
                                        }else{
                                            $address['city_index'] = 0;
                                        }
                                        $address['city_id'] = $tmp_address['pid'];
                                        $address['city_name'] = $p_address['name'];
                                        $district_index = array_search($tmp_address['id'], $area_model->where('level', 2)->column('id'));
                                        if($district_index !== false){
                                            $address['district_index'] = $district_index;
                                        }else{
                                            $address['district_index'] = 0;
                                        }
                                        $address['district_id'] = $tmp_address['id'];
                                        $address['district_name'] = $tmp_address['name'];
                                    }else{
                                        $province_index = array_search($p_address['id'], $area_model->where('level', 0)->column('id'));
                                        if($province_index !== false){
                                            $address['province_index'] = $province_index;
                                        }else{
                                            $address['province_index'] = 0;
                                        }
                                        $address['province_id'] = $p_address['id'];
                                        $address['province_name'] = $p_address['name'];
                                        $city_index = array_search($tmp_address['id'], $area_model->where('level', 1)->where('pid', $p_address['pid'])->column('id'));
                                        if($city_index !== false){
                                            $address['city_index'] = $city_index;
                                        }else{
                                            $address['city_index'] = 0;
                                        }
                                        $address['city_id'] = $tmp_address['id'];
                                        $address['city_name'] = $tmp_address['name'];
                                        $address['district_index'] = 0;
                                        $address['district_id'] = 0;
                                        $address['district_name'] = '';
                                    }
                                }
                            }else {
                                $province_index = array_search($tmp_address['id'], $area_model->where('level', 0)->column('id'));
                                if($province_index !== false){
                                    $address['province_index'] = $province_index;
                                }else{
                                    $address['province_index'] = 0;
                                }
                                $address['province_id'] = $tmp_address['id'];
                                $address['province_name'] = $tmp_address['name'];
                                $address['city_index'] = 0;
                                $address['city_id'] = 0;
                                $address['city_name'] = '';
                                $address['district_index'] = 0;
                                $address['district_id'] = 0;
                                $address['district_name'] = '';
                            }
                        }else{
                            $address['province_index'] = 0;
                            $address['province_id'] = 0;
                            $address['province_name'] = '';
                            $address['city_index'] = 0;
                            $address['city_id'] = 0;
                            $address['city_name'] = '';
                            $address['district_index'] = 0;
                            $address['district_id'] = 0;
                            $address['district_name'] = '';
                        }
                            if(!empty($address['province_id'])){
//                                $province_index = array_search($address['province_id'], $area_model->where('level', 0)->column('id'));
//                                if($province_index !== false){
//                                    $address['province_index'] = $province_index;
//                                    $city_index = array_search($address['city_id'], $area_model->where('pid', $address['province_id'])->where('level', 1)->column('id'));
//                                    if($city_index !== false){
//                                        $address['city_index'] = $city_index;
//                                    }
//                                    $district_index = array_search($address['district_id'], $area_model->where('pid', $address['city_id'])->where('level', 2)->column('id'));
//                                    if($district_index !== false){
//                                        $address['district_index'] = $district_index;
//                                    }
//                                }
//                            }
                        }
//                        var_dump($address);
//                        $address = $area_model->alias('d')
//                            ->join('jieziarea c', 'd.pid = c.id')
//                            ->join('jieziarea p', 'c.pid = p.id')
//                            ->where('d.id', $res['result']['ad_info']['adcode'])
//                            ->field('c.id as city_id, c.name as city_name, d.id as district_id, d.name as district_name, p.id as province_id, p.name as province_name')->find();
//                        var_dump($address, $area_model->getLastSql());
//                        if(!empty($address)){
//                            if(!empty($address['province_id'])){
//                                $province_index = array_search($address['province_id'], $area_model->where('level', 0)->column('id'));
//                                if($province_index !== false){
//                                    $address['province_index'] = $province_index;
//                                    $city_index = array_search($address['city_id'], $area_model->where('pid', $address['province_id'])->where('level', 1)->column('id'));
//                                    if($city_index !== false){
//                                        $address['city_index'] = $city_index;
//                                    }
//                                    $district_index = array_search($address['district_id'], $area_model->where('pid', $address['city_id'])->where('level', 2)->column('id'));
//                                    if($district_index !== false){
//                                        $address['district_index'] = $district_index;
//                                    }
//                                }
//                            }
//                        }
//                        可能是直辖市，所以再获取两级的试试
                    }
                }
            }else{
                $address = $res;
            }
        }
        return $address;
    }

    public function getLatLngByQqmap($address){
        $addon_config = get_addon_config('jieziarea');
        $qqmap_service_key = empty($addon_config['qqmap_service_key']) ? '' : $addon_config['qqmap_service_key'];
        $qqmap_service_sk = empty($addon_config['qqmap_service_sk']) ? '' : $addon_config['qqmap_service_sk'];
        $qqmap_service_key = config('site.qqmap_service_key');
        $qqmap_service_sk = config('site.qqmap_service_sk');
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/?address=' . $address . '&key='.$qqmap_service_key . '&sig=' . md5('/ws/geocoder/v1/?address=' . $address . '&key=' . $qqmap_service_key . $qqmap_service_sk);
        $res = file_get_contents($url, false, stream_context_create(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]));
        $res = json_decode($res, true);//var_dump($res['regeocode']);
//        var_dump($res);
        if(!$res['status']){
            $fulladdress = '';
            $address = $res['result']['title'];
            $address_components = $res['result']['address_components'];
            if(strpos($address, $address_components['province']) === false) {
                $fulladdress .= $address_components['province'];
            }
            if(strpos($address, $address_components['city']) === false) {
                $fulladdress .= $address_components['city'];
            }
            if(strpos($address, $address_components['district']) === false) {
                $fulladdress .= $address_components['district'];
            }
            if($address_components['street'] && strpos($address, $address_components['street']) === false) {
                $fulladdress .= $address_components['street'];
            }
            $fulladdress .= $address;

            $result = [
                'status' => $res['status'],
                'title' => $address,
                'lat' => $res['result']['location']['lat'],
                'lng' => $res['result']['location']['lng'],
                'level' => $res['result']['level'],
                'fulladdress' => $fulladdress,
            ];
        }else{
            $result = [
                'status' => $res['status'],
                'msg' => $res['message'],
            ];
        }
        return $result;
    }


    public function getIpLatLngByQqmap($ip = ''){
        if(empty($ip)){
            $ip = request()->ip();
        }
        $url = 'https://apis.map.qq.com/ws/location/v1/ip?ip=' . $ip . '&key='.config('app.qqmap_ws');
        $res = file_get_contents($url, false, stream_context_create(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]));
        $res = json_decode($res, true);//var_dump($res['regeocode']);
        if(!$res['status']){
            $result = [
                'status' => $res['status'],
//                'title' => $res['result']['title'],
                'lat' => $res['result']['location']['lat'],
                'lng' => $res['result']['location']['lng'],
            ];
        }else{
            $result = [
                'status' => $res['status'],
                'msg' => $res['message'],
            ];
        }
        return $result;
    }
}